//
//  ViewController.swift
//  二维码扫描
//
//  Created by Nick xu on 16/8/3.
//  Copyright © 2016年 hddden. All rights reserved.
//
    

import UIKit
import Foundation
import AVFoundation

class AVQRCodeViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
    //MARK: - property
    let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
    let session = AVCaptureSession()
    var layer : AVCaptureVideoPreviewLayer?
    //MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        //添加边框
        let imageView = UIImageView(frame: CGRect(x: 10, y: 100, width: 300, height: 300))
        imageView.image = UIImage(named: "pick_bg")
        self.view.addSubview(imageView)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.setupCamera()
        self.session.startRunning()
    }
    
    //MARK: - private
    func setupCamera(){
        //TODO: 高质量采集率
        self.session.sessionPreset = AVCaptureSessionPresetHigh
        var error : NSError?
         //TODO: 输入流
        let input: AVCaptureDeviceInput!
        do{
            input = try AVCaptureDeviceInput(device: device)
        }
        catch let error1 as NSError{
            error = error1
            input = nil
        }
        if error != nil {
            return
        }
        if session.canAddInput(input) {
            session.addInput(input)
        }
         //TODO: 显示图像
        layer = AVCaptureVideoPreviewLayer(session: session)
        layer!.videoGravity = AVLayerVideoGravityResizeAspectFill
        layer!.frame = CGRect(x: 20, y: 110, width: 280, height: 280)
        self.view.layer.insertSublayer(self.layer!, at: 0)
        let output = AVCaptureMetadataOutput()
        output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        if session.canAddOutput(output) {
            session.addOutput(output)
            //设置扫码支持的编码格式（如下设置各种条形码和二维码兼容）
            output.metadataObjectTypes = [ AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeUPCECode,AVMetadataObjectTypePDF417Code,
                                           AVMetadataObjectTypeAztecCode,
                                           AVMetadataObjectTypeCode93Code,
                                           AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeCode39Mod43Code];
            //            output.rectOfInterest = CGRectMake(0, 0, 1, 0)
        }
        session.startRunning()
    }
    
    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
        
//        var stringValue:String?
//        if metadataObjects.count > 0 {
//            let metadataObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
//            stringValue = metadataObject.stringValue
//        }
        self.session.stopRunning()
//        print("code is \(stringValue)")
    }


}

